/*
 * Copyright (c) 2012 by Chances.
 * $CVSHeader$
 * $Author: shenwei $
 * $Date: 2017-07-17 12:41:35 +0800 (星期一, 17 七月 2017) $
 * $Revision: 6 $
 */
package mxmf.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import chances.smart.commons.mvc.interceptor.OpInfo;
import mxmf.ctrl.model.PageBean;
import mxmf.utils.BeanUtilsHelper;
import mxmf.utils.PermissionHelper;

public abstract class AbstractController {
    
    @Autowired
    private PermissionHelper permissionHelper;

    protected BeanUtilsHelper beanUtilsHelper = BeanUtilsHelper.getInstance("yyyy-MM-dd HH:mm:ss");

    public static final int SUCCESS = 200;

    // 系统错误：9
    public static final int ERROR = 9999;

    private static final String UN_KNOW = "unknown";

    protected PageBean createPageBean(int size, int curPage) {
        PageBean pageBean = new PageBean(size);
        pageBean.setCurrentPage(curPage);
        return pageBean;
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || (UN_KNOW.equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || (UN_KNOW.equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || (UN_KNOW.equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    protected void setAttribute(String name, Object obj) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        request.setAttribute(name, obj);
    }

    protected OpInfo getOpInfo() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        return (OpInfo) request.getAttribute(OpInfo.class.getSimpleName());
    }

    protected String[] getCpCodes() {
        return permissionHelper.getCpCodes();
    }

    protected String[] getTypeCodes() {
        return permissionHelper.getTypeCodes();
    }

    protected String[] getOpCodes() {
        return permissionHelper.getOpCodes();
    }

    protected String getUserId() {
        return getOpInfo() != null ? getOpInfo().getLoginName() : null;
    }

    protected List<String> getRoleCodes() {
        return getOpInfo() != null ? getOpInfo().getRoles() : new ArrayList<>();
    }

}
